#pragma once
#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <cerrno> 
class TCPClient
{
public: 
    // 传入IP和端口号
    TCPClient(const std::string &_serverip, int _serverport) : _clientsockfd(-1), _serverip(_serverip), _serverport(_serverport), _isconnected(false)
    {
        memset(&_serveraddr, 0, sizeof(_serveraddr));
        _serveraddr.sin_family = AF_INET;
        _serveraddr.sin_port = htons(_serverport);
        if (inet_pton(AF_INET, _serverip.c_str(), &_serveraddr.sin_addr) <= 0)
        {
            std::cerr << "Invalid server IP address format: " << _serverip << std::endl;
        }
    }

    ~TCPClient()
    {}

    bool connectToServer()
    {
        _clientsockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_clientsockfd < 0)
        {
            std::cerr << "创建失败~" << strerror(errno) << std::endl;
            return false;
        }
        std::cout << "创建成功~" << std::endl;
        if(connect(_clientsockfd, (struct sockaddr *)&_serveraddr, sizeof(_serveraddr)) < 0)
        {
            std::cerr << "连接失败~" << strerror(errno) << std::endl;
            close(_clientsockfd);
            _clientsockfd = -1;
            return false;
        }
        std::cout << "连接成功~" << std::endl;
        _isconnected = true;
        return true;
    }


    bool sendMsg(const std::string &message)
    {
        if (!_isconnected)
        {
            std::cerr << "没连接哦~" << std::endl;
            return false;
        }

        ssize_t s = send(_clientsockfd, message.c_str(), message.size(), 0);
        if (s < 0)
        {
            std::cerr << "发送失败~" << strerror(errno) << std::endl;
            return false;
        }
        std::cout << "发送成功~" << std::endl;
        return true;
    }

    std::string receive()
    {
        if (!_isconnected)
        {
            std::cerr << "没连接哦~" << std::endl;
            return std::string();
        }

        char buf[1024];
        ssize_t r = recv(_clientsockfd,buf,1024,0);
        if (r < 0)
        {
            std::cerr << "接收失败~" << strerror(errno) << std::endl;
            return std::string();
        }
        std::cout << "接收成功~" << std::endl;
        return std::string(buf,r);
    }

    void disconnect()
    {
        if (_isconnected)
        {
            close(_clientsockfd);
            _clientsockfd = -1;
            _isconnected = false;
            std::cout << "断开连接~" << std::endl;
        }
        else
        {
            std::cerr << "没连接哦~" << std::endl;
        }
    }
private:
    int _clientsockfd;
    std::string _serverip;
    int _serverport;
    struct sockaddr_in _serveraddr;
    bool _isconnected;
};